package com.chauncy.DMS.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.chauncy.DMS.bean.ManagerInfoBean;
import com.chauncy.DMS.dao.ManagerDaoImplement;

public class ManagerLoginServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

			String flag = request.getParameter("logout");
			//System.out.println(flag);
			if(flag.equals("logout")){
				logout(request, response);
				response.sendRedirect("./index.jsp");
			}
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

				//获取登陆用户名/用户工号
				String managerName = request.getParameter("managerName");
				//获取登陆密码
				String managerPassword = request.getParameter("managerPassword");
				ManagerInfoBean managerInfoBean = new ManagerInfoBean();
				//将获取值赋值给bean类 
				managerInfoBean.setEmp_no(managerName);
				managerInfoBean.setManager_name(managerName);
				managerInfoBean.setManager_pwd(managerPassword);	
				//调用dao中的管理员登陆方法 进行登陆验证
				ManagerDaoImplement daoImplement = new ManagerDaoImplement();
				//登陆返回值为一个list
				List<ManagerInfoBean> managerList = new ArrayList<ManagerInfoBean>();
				try {
					managerList = daoImplement.managerLogin(managerInfoBean);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//判断list是否为空，确定是否成功登陆
				if(managerList != null && managerList.size() > 0){
					HttpSession httpSession  = request.getSession();
					httpSession.setAttribute("managerInfoList",managerList);
					response.getWriter().print("managerExist");
				}else{
					response.getWriter().print("managerNotExist");
				}
				if(request.getParameter("managerFlag") != null && !request.getParameter("managerFlag").equals("")){
					try {
						changePageToSystem(request,response);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
	}
	private static void logout(HttpServletRequest request ,HttpServletResponse response){
		request.getSession().invalidate();
	}
	//跳转到系统主页
	private static void changePageToSystem(HttpServletRequest request ,
			HttpServletResponse response)
				throws Exception{
			response.sendRedirect("./managerPage/maneger_page.jsp");
	}

}
